package api

import (
	"fmt"
	"bytes"
	"bufio"
	"net/http"
	"io/ioutil"
	"encoding/json"
	"read.com/wxmp/handler"
)

type WechatMessage struct {
	ToUser  string         `json:"touser"`
	MsgType string         `json:"msgtype"`
	Text    MessageContent `json:"text"`
}

type MessageContent struct {
	Content string `json:"content"`
}

// 客服消息
func SendCustomMessage(token, toUser, content string) {
	sign := WechatMessage{
		ToUser:  toUser,
		MsgType: "text",
		Text: MessageContent{
			Content: content,
		},
	}
	buf := bytes.NewBuffer(make([]byte, 0))
	writer := bufio.NewWriter(buf)
	enc := json.NewEncoder(writer)
	enc.SetEscapeHTML(false)
	enc.Encode(sign)
	writer.Flush()

	ulrStr := "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token
	if data, err := PostJsonRequest(ulrStr, buf.Bytes()); err == nil {
		resp := &WechatError{}
		if err = json.Unmarshal(data, resp); err != nil {
			fmt.Println("客服消息发送，应答解析json错误.", err)
		} else if resp.ErrCode != 0 {
			fmt.Println("客服消息发送，应答失败.", string(data))
		}
	}
}

// 发送图文消息(继续阅读+小说推荐，图文链接)
func SendImgMsg(token string,imgTextMsg handler.ImgTextMsg){
	imgTextMsgData, err := json.Marshal(imgTextMsg)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(string(imgTextMsgData))
	}
	urlReq := "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token
	PostJsonRequest(urlReq,imgTextMsgData)
}

func PostJsonRequest(url string, data []byte) ([]byte, error) {
	postReq, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
	if err != nil {
		fmt.Println("创建POST请求失败:", err, url)
		return nil, err
	}
	postReq.Header.Set("Content-type", "application/json;encoding=utf-8;")
	postReq.Close = true

	client := &http.Client{}
	resp, err := client.Do(postReq)
	if err != nil {
		fmt.Println("向微信发起请求失败:", err, url)
		return nil, err
	}

	defer resp.Body.Close()
	if body, err := ioutil.ReadAll(resp.Body); err != nil {
		fmt.Println("微信应答错误:", err, url, string(body))
		return nil, err
	} else {
		return body, err
	}
}
